﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CrpytDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = "adminEncry12345765";
            string key = "zhangsan";// "19711203";
            string iv = "20220422";
            MyDESUtil dESUtil = new MyDESUtil();
            byte[] res = dESUtil.EncryStr(Encoding.UTF8.GetBytes(data), key);
            Console.WriteLine("Encry = " + Convert.ToBase64String(res));
            Console.WriteLine("Encry = " + BitConverter.ToString(res));
            byte[] resDecry = dESUtil.DecryStr(res, key);
            Console.WriteLine("Decry = " + Encoding.UTF8.GetString(resDecry).TrimEnd('\0'));


            res = dESUtil.EncryCBCStr(Encoding.UTF8.GetBytes(data), key, iv);
            Console.WriteLine("Encry CBC = " + Convert.ToBase64String(res));
            Console.WriteLine("Encry CBC = " + BitConverter.ToString(res));
            resDecry = dESUtil.DecryCBCStr(res, key, iv);
            Console.WriteLine("Decry CBC = " + Encoding.UTF8.GetString(resDecry).TrimEnd('\0'));



            Console.WriteLine("C# Encry = " + DESEncryptString(data, key));
            Console.WriteLine("C# Encry CBC = " + DESEncryptString(data, key, CipherMode.CBC, iv));
            Console.ReadLine();
        }

        static string DESEncryptString(string Value , string key, CipherMode mode= CipherMode.ECB, string iv = "20220101")
        {

            if (string.IsNullOrEmpty(Value))
                return null;
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;

            try
            {
                DESCryptoServiceProvider mCSP = new DESCryptoServiceProvider();
                mCSP.Key = Encoding.UTF8.GetBytes(key);
                mCSP.IV = Encoding.UTF8.GetBytes(iv);
                mCSP.Mode = mode;
                mCSP.Padding = PaddingMode.PKCS7;
                Console.WriteLine("DES KEY : " + BitConverter.ToString(mCSP.Key));
                Console.WriteLine("DES IV  : " + BitConverter.ToString(mCSP.IV));
                ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
                byt = Encoding.UTF8.GetBytes(Value);

                Console.WriteLine("DES DATA: " + BitConverter.ToString(byt));
                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();

                cs.Close();
                byte[] resData = ms.ToArray();
                Console.WriteLine("DES = " + BitConverter.ToString(resData));
                return Convert.ToBase64String(resData);
            }
            catch (Exception e)
            {
                //Logger.Error(e.Message);
                return null;
            }
        }
    }
}
